<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试音频生成器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            margin: 0;
        }

        .container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 2rem;
            max-width: 500px;
            width: 90%;
            text-align: center;
        }

        h1 {
            margin-bottom: 2rem;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }

        .form-group {
            margin-bottom: 1.5rem;
            text-align: left;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }

        input, select {
            width: 100%;
            padding: 0.8rem;
            border: none;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.9);
            color: #333;
            font-size: 1rem;
        }

        .btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            color: white;
            padding: 1rem 2rem;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            margin: 0.5rem;
            transition: transform 0.2s;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        .preview {
            margin-top: 1rem;
            padding: 1rem;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 8px;
        }

        #status {
            margin-top: 1rem;
            padding: 1rem;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎵 测试音频生成器</h1>
        
        <div class="form-group">
            <label for="duration">音频时长（秒）:</label>
            <input type="number" id="duration" value="120" min="10" max="300">
        </div>

        <div class="form-group">
            <label for="waveType">波形类型:</label>
            <select id="waveType">
                <option value="sine">正弦波</option>
                <option value="square">方波</option>
                <option value="sawtooth">锯齿波</option>
                <option value="triangle">三角波</option>
                <option value="complex">复合音频</option>
            </select>
        </div>

        <div class="form-group">
            <label for="baseFreq">基础频率（Hz）:</label>
            <input type="number" id="baseFreq" value="440" min="100" max="2000">
        </div>

        <button id="generateBtn" class="btn">🎼 生成音频</button>
        <button id="playBtn" class="btn" disabled>▶️ 预览</button>
        <button id="downloadBtn" class="btn" disabled>💾 下载</button>

        <div id="preview" class="preview" style="display: none;">
            <audio id="audioPlayer" controls style="width: 100%;"></audio>
        </div>

        <div id="status">点击"生成音频"创建测试文件</div>
    </div>

    <script>
        class AudioGenerator {
            constructor() {
                this.audioContext = null;
                this.audioBuffer = null;
                this.audioBlob = null;
                
                this.generateBtn = document.getElementById('generateBtn');
                this.playBtn = document.getElementById('playBtn');
                this.downloadBtn = document.getElementById('downloadBtn');
                this.audioPlayer = document.getElementById('audioPlayer');
                this.preview = document.getElementById('preview');
                this.status = document.getElementById('status');
                
                this.bindEvents();
            }

            bindEvents() {
                this.generateBtn.addEventListener('click', () => this.generateAudio());
                this.playBtn.addEventListener('click', () => this.playAudio());
                this.downloadBtn.addEventListener('click', () => this.downloadAudio());
            }

            async generateAudio() {
                const duration = parseInt(document.getElementById('duration').value);
                const waveType = document.getElementById('waveType').value;
                const baseFreq = parseInt(document.getElementById('baseFreq').value);

                this.status.textContent = '正在生成音频...';
                this.generateBtn.disabled = true;

                try {
                    if (!this.audioContext) {
                        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
                    }

                    const sampleRate = this.audioContext.sampleRate;
                    const length = duration * sampleRate;
                    const buffer = this.audioContext.createBuffer(2, length, sampleRate);

                    // 生成音频数据
                    for (let channel = 0; channel < 2; channel++) {
                        const channelData = buffer.getChannelData(channel);
                        
                        for (let i = 0; i < length; i++) {
                            const time = i / sampleRate;
                            let sample = 0;

                            if (waveType === 'complex') {
                                // 创建复合音频 - 模拟音乐的复杂性
                                const freq1 = baseFreq * (1 + Math.sin(time * 0.5) * 0.1);
                                const freq2 = baseFreq * 1.5 * (1 + Math.sin(time * 0.3) * 0.05);
                                const freq3 = baseFreq * 2 * (1 + Math.sin(time * 0.7) * 0.03);
                                
                                sample = Math.sin(2 * Math.PI * freq1 * time) * 0.4 +
                                        Math.sin(2 * Math.PI * freq2 * time) * 0.3 +
                                        Math.sin(2 * Math.PI * freq3 * time) * 0.2;
                                
                                // 添加低频重音模式
                                const beat = Math.sin(2 * Math.PI * time * 2) > 0.8 ? 1.5 : 1;
                                sample *= beat;
                                
                                // 添加渐变效果
                                const fadeIn = Math.min(1, time * 2);
                                const fadeOut = Math.min(1, (duration - time) * 2);
                                sample *= fadeIn * fadeOut;
                                
                            } else {
                                // 简单波形
                                const freq = baseFreq + Math.sin(time * 0.5) * 50;
                                
                                switch (waveType) {
                                    case 'sine':
                                        sample = Math.sin(2 * Math.PI * freq * time);
                                        break;
                                    case 'square':
                                        sample = Math.sign(Math.sin(2 * Math.PI * freq * time));
                                        break;
                                    case 'sawtooth':
                                        sample = 2 * (freq * time % 1) - 1;
                                        break;
                                    case 'triangle':
                                        const t = freq * time % 1;
                                        sample = t < 0.5 ? 4 * t - 1 : 3 - 4 * t;
                                        break;
                                }
                                
                                // 添加包络
                                const envelope = Math.sin(Math.PI * time / duration);
                                sample *= envelope * 0.5;
                            }

                            channelData[i] = sample * 0.3; // 降低音量避免失真
                        }
                    }

                    this.audioBuffer = buffer;
                    
                    // 转换为可下载的文件
                    await this.bufferToWav(buffer);
                    
                    this.playBtn.disabled = false;
                    this.downloadBtn.disabled = false;
                    this.status.textContent = `音频生成成功！时长: ${duration}秒`;
                    
                } catch (error) {
                    console.error('音频生成失败:', error);
                    this.status.textContent = '音频生成失败，请重试';
                } finally {
                    this.generateBtn.disabled = false;
                }
            }

            async bufferToWav(buffer) {
                const length = buffer.length;
                const sampleRate = buffer.sampleRate;
                const arrayBuffer = new ArrayBuffer(44 + length * 4);
                const view = new DataView(arrayBuffer);

                // WAV文件头
                const writeString = (offset, string) => {
                    for (let i = 0; i < string.length; i++) {
                        view.setUint8(offset + i, string.charCodeAt(i));
                    }
                };

                writeString(0, 'RIFF');
                view.setUint32(4, 36 + length * 4, true);
                writeString(8, 'WAVE');
                writeString(12, 'fmt ');
                view.setUint32(16, 16, true);
                view.setUint16(20, 1, true);
                view.setUint16(22, 2, true);
                view.setUint32(24, sampleRate, true);
                view.setUint32(28, sampleRate * 4, true);
                view.setUint16(32, 4, true);
                view.setUint16(34, 16, true);
                writeString(36, 'data');
                view.setUint32(40, length * 4, true);

                // 音频数据
                const leftChannel = buffer.getChannelData(0);
                const rightChannel = buffer.getChannelData(1);
                let offset = 44;
                
                for (let i = 0; i < length; i++) {
                    view.setInt16(offset, leftChannel[i] * 0x7FFF, true);
                    view.setInt16(offset + 2, rightChannel[i] * 0x7FFF, true);
                    offset += 4;
                }

                this.audioBlob = new Blob([arrayBuffer], { type: 'audio/wav' });
                
                // 设置预览
                const url = URL.createObjectURL(this.audioBlob);
                this.audioPlayer.src = url;
                this.preview.style.display = 'block';
            }

            playAudio() {
                if (this.audioPlayer.src) {
                    this.audioPlayer.play();
                }
            }

            downloadAudio() {
                if (this.audioBlob) {
                    const url = URL.createObjectURL(this.audioBlob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `test-audio-${Date.now()}.wav`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            new AudioGenerator();
        });
    </script>
</body>
</html>
